if GLOBAL.TheNet:IsDedicated() or GLOBAL.TheNet:GetServerGameMode() == "lavaarena" then return end
-- 额外地图图标
local t_util = require "libs/tableutil"
local map_data = {}
local tonumber = GLOBAL.tonumber
local iscave = 0
local e_util = require "libs/entutil"

local wormhole_path = "images/wormhole_num_new"
local tentapillar_path = "images/tentapillar_num_new"
local xml_path = wormhole_path..".xml"
local img_path = "wormhole_"

-- 原理：
-- 一、消失的时候：
-- 1、动画非死亡，且没有跟随：移除该标记周围的标记，并增加1标记
-- 2、路过的时候：移除范围内所有标记，生成对应标记


local function getPos(ent)
    if ent and ent.Transform then
        local x,_,z = ent.Transform:GetWorldPosition()
        if x and z then
            return string.format("%.2f", x),string.format("%.2f", z)
        end
    end
end



----------------------------- 日常任务 ---------------------------------------------------
local function showinmap(inst)
    if GetAnim(inst) ~= "death" and not GetLeader(inst) then
        local ix,iz = getPos(inst)
        local prefab = inst.prefab
        if ix and iz and prefab then
            for id, data in pairs(map_data)do
                if type(data) == "table" and data.p == prefab then
                    local dx, dz = tonumber(data.x), tonumber(data.z)
                    if dx and dz and data.c == iscave and GetDist(ix,iz,dx,dz)<8 then
                        map_data[id] = nil
                    end
                end
            end
            table.insert(map_data, {
                c = iscave,
                x = ix,
                z = iz,
                p = prefab,
            })
        end
    end
end
-- prefabs 的 东西会在扫描列表
local icondata = require("QAQ/icondata")
local prefabs = {}
for prefab,_ in pairs(icondata)do
    table.insert(prefabs, prefab)
    AddPrefabPostInit(prefab, function(inst)
        inst:ListenForEvent("onremove", showinmap)
        inst:DoTaskInTime(1, showinmap)
    end)
end
----------------------------- 日常任务 ---------------------------------------------------




----------------------------------······海难适配-------------------------------------·········
-- 唯一的标识，此处添加的话不受生物死亡或消失的影响，可以用来增加建筑物或刷新点的标记
-- 无法自动取消，可以通过面板删除
local fixeddata = {
    swordfish_spawner = {
        image = "hambat_nautical.tex",
        atlas = GLOBAL.GetInventoryItemAtlas("hambat_nautical.tex"),
    }
}
for prefab,data in pairs(fixeddata)do
    AddPrefabPostInit(prefab, function(inst)
        inst:DoTaskInTime(0.5, function(inst)
            local ix,iz = getPos(inst)
            local flag
            for id, data in pairs(map_data)do
                if type(data) == "table" and data.p == prefab then
                    local dx, dz = tonumber(data.x), tonumber(data.z)
                    if dx and dz and data.c == iscave and GetDist(ix,iz,dx,dz)<64 then
                        flag = true
                        break
                    end
                end
            end
            if not flag and ix and iz then
                table.insert(map_data, {
                    c = iscave,
                    x = ix,
                    z = iz,
                    p = prefab,      -- 传prefab没有实际意义
                    l = 0, -- 此标识用来路过检测，有此标记则不检测
                    image = data.image,
                    atlas = data.atlas,
                })
            end
        end)
        
    end)
end
----------------------------------······海难适配-------------------------------------·········


----------------------------------------虫洞标记-----------------------------------------------
-- 虫洞标记
local wormhole_prefabs = {"tentacle_pillar_hole", "tentacle_pillar", "wormhole", "ndpr_wormhole",}
local function GetWormhole()
    return e_util:FindEnt(true, wormhole_prefabs, 5, {"teleporter"})
end
local function IsHoleTableExist(x, z, prefab)
    for _, data in pairs(map_data)do
        if type(data) == "table" and data.p == prefab and data.x == x and data.z == z and iscave==data.c then
            local img = data.image
            local num = type(img) == "string" and string.match(img, "%d+")
            return GLOBAL.tonumber(num)
        end
    end
end
local function IsShortTime()
    return GLOBAL.MOD_ShroomCake.Setting.wormholecheck and GLOBAL.MOD_ShroomCake.Func.TryCraft and GLOBAL.MOD_ShroomCake.Func.TryCraft(true)
end
local RGB = GLOBAL.RGB
local colors = {
    RGB(255, 0, 32),    -- red
    RGB(0, 225, 255),   -- teal
    RGB(96, 64, 255),   -- purple
    RGB(0, 255, 75),    -- green
    RGB(255, 75, 0),    -- orange
    RGB(0, 128, 255),   -- blue
    RGB(96, 200, 32),   -- lime
    RGB(255, 32, 128),  -- pink
    RGB(182, 255, 0),   -- yellow
    RGB(64, 64, 64),    -- gray
}
local function AddWormhole(inst)
    local pos_x, pos_z = getPos(inst)
    local prefab = inst.prefab
    if pos_x and pos_z and prefab and not inst.border_circle then
        local key = IsHoleTableExist(pos_x, pos_z, prefab)
        if key and key <= 10 then
            local add_color = 0.15
            inst.AnimState:SetAddColour(add_color, add_color, add_color, 0)
            inst.AnimState:OverrideMultColour(GLOBAL.unpack(colors[key]))
            if prefab == "wormhole" then
                inst.AnimState:SetLayer(GLOBAL.LAYER_WORLD_BACKGROUND)
            end
            
            local label = inst.entity:AddLabel()
            label:SetFont(GLOBAL.CHATFONT_OUTLINE)
            label:SetFontSize(35)
            label:SetWorldOffset(0, 2, 0)
            label:SetText(key.."")
            label:SetColour(GLOBAL.unpack(colors[key]))
            label:Enable(true)

            
            inst.border_circle = inst:SpawnChild("border_circle")
            inst.border_circle.AnimState:SetAddColour(GLOBAL.unpack(colors[key]))
        end
    end
end
local changecolor = GetModConfigData("sw_moreicons") ~= "onlymap"
if changecolor then
    for _, prefab in pairs(wormhole_prefabs)do
        AddPrefabPostInit(prefab, function(inst)
            inst:DoTaskInTime(0, AddWormhole)
        end)
    end
end
AddPrefabPostInit("player_classified", function(player_classified)
    player_classified:ListenForEvent("wormholetraveldirty", function()
        local entrance = GetWormhole()
        local in_x, in_z = getPos(entrance)
        if in_x and not IsHoleTableExist(in_x, in_z, entrance.prefab) then
            local waitTime = IsShortTime() and 1 or 3
            GLOBAL.ThePlayer:DoTaskInTime(waitTime, function()
                local exit = GetWormhole()
                local out_x, out_z = getPos(exit)
                if out_x and not IsHoleTableExist(out_x, out_z, exit.prefab) then
                    local h_icons = {}                  -- 已存在的图标
                    for id, data in pairs(map_data)do
                        if type(data) == "table" and xml_path==data.atlas and data.image then
                            h_icons[data.image] = true
                        end
                    end
                    for i = 1,10 do
                        local tex = img_path..i..".tex"
                        if not h_icons[tex] then
                            -- 两个虫洞入库
                            table.insert(map_data, {c = iscave, x = in_x, z = in_z, p = exit.prefab, l = 0, image = tex, atlas = xml_path})
                            table.insert(map_data, {c = iscave, x = out_x, z = out_z, p = exit.prefab, l = 0, image = tex, atlas = xml_path})
                            -- 虫洞染色
                            if changecolor then
                                AddWormhole(entrance)
                                AddWormhole(exit)
                            end
                            break
                        end
                    end
                end
            end)
        end
    end)
end)
----------------------------------------虫洞标记-----------------------------------------------



---------------------------------------风滚草预测-----------------------------------------------
local recordTime = 0
local shortTime = 0.5
local minPoses = 4          -- 每四个风滚草为一个刷新点
local tw_poses = {}
-- local recordPoses = {}
local c_util = require "libs/calcutil"
local d_util = require "libs/datamanager"


local function notCheckTW(pos, now)
    if now - recordTime > shortTime then return true end
    for _, tw_pos in pairs(tw_poses) do
        local dist = c_util:GetDist(pos.x, pos.z, tw_pos.x, tw_pos.z)
        if dist > 8 then return true end
    end
end
AddPrefabPostInit("tumbleweed", function(inst)
    inst:DoTaskInTime(0.25, function(inst)
        local pos = inst.Transform and inst:GetPosition()
        if type(pos)~="table" or pos.x == 0 then return end
        local now = GLOBAL.GetTime()
        if notCheckTW(pos, now) then tw_poses = {} end
        recordTime = now
        table.insert(tw_poses, pos)
        if #tw_poses ~= minPoses then return end
        local recordPos = {}
        for _, tw_pos in pairs(tw_poses) do
            if not recordPos.x or not recordPos.y then
                recordPos = tw_pos
            else
                recordPos.x = (tw_pos.x + recordPos.x) / 2
                recordPos.z = (tw_pos.z + recordPos.z) / 2
            end
        end

        local h_data = d_util:GetIconData()
        for _, line in pairs(h_data)do
            if line.i == "huxi_tumbleweed.tex" then
                return
            end
        end

        local prefab = "huxi_tumbleweed"
        local newPoint = GLOBAL.SpawnPrefab(prefab)
        newPoint.Transform:SetPosition(recordPos.x, 0, recordPos.z)
        local ix,iz = getPos(newPoint)
        for id, data in pairs(map_data)do
            if type(data) == "table" and data.p == prefab then
                local dx, dz = tonumber(data.x), tonumber(data.z)
                if dx and dz and data.c == iscave and GetDist(ix,iz,dx,dz)<8 then
                    map_data[id] = nil
                end
            end
        end
        table.insert(map_data, {
            c = iscave,
            x = ix,
            z = iz,
            p = prefab,
            l = 0,
            atlas = "images/shroomcake_moreicons.xml",
            image = "huxi_tumbleweed.tex",
            m = 0,      -- 拥有此标记时，将扫面该点附近的"huxi"标签并重新设立位置
        })
        -- table.insert(recordPoses, recordPos)
    end)
end)
---------------------------------------风滚草预测-----------------------------------------------

---------------------------------------蘑菇地精刷新----------------------------------------------
AddPrefabPostInit("mushgnome", function(inst)
    inst:DoTaskInTime(0.25, function(inst)
        local pos = inst.Transform and inst:GetPosition()
        if type(pos)~="table" or pos.x == 0 then return end

        local h_data = d_util:GetIconData()
        for _, line in pairs(h_data)do
            if line.i == "huxi_mushgnome.tex" then
                return
            end
        end

        local prefab = "huxi_mushgnome"
        local newPoint = GLOBAL.SpawnPrefab(prefab)
        newPoint.Transform:SetPosition(pos.x, 0, pos.z)
        local ix,iz = getPos(newPoint)
        for id, data in pairs(map_data)do
            if type(data) == "table" and data.p == prefab then
                local dx, dz = tonumber(data.x), tonumber(data.z)
                if dx and dz and data.c == iscave and GetDist(ix,iz,dx,dz)<20 then
                    map_data[id] = nil
                end
            end
        end
        table.insert(map_data, {
            c = iscave,
            x = ix,
            z = iz,
            p = prefab,
            l = 0,
            atlas = "images/shroomcake_moreicons.xml",
            image = "huxi_mushgnome.tex",
            m = 0,      -- 拥有此标记时，将扫面该点附近的"huxi"标签并重新设立位置
        })
    end)
end)
---------------------------------------蘑菇地精刷新----------------------------------------------

-----------------------------------------核心原理-----------------------------------------------
-- 核心，每5s扫描一次玩家附近的图标
local __ConfirmPlayerInitializationTheLock
local range = 60
local stop_watch_5 = 0
AddPlayerActivatedFunc(function(player, world)
    if not __ConfirmPlayerInitializationTheLock then
        map_data = require("libs/worldmanager"):GetWorldDataList("more_map_icons")
        __ConfirmPlayerInitializationTheLock = true
        local c = world:HasTag("cave")
        iscave = c and 1 or 0
        xml_path = (c and tentapillar_path or wormhole_path)..".xml"
        img_path = c and "tentapillar_" or "wormhole_"
    end
    -- 玩家5s走30个地皮
    player:ListenForEvent("position_withhx", function(player, data_pos)
        local now = GLOBAL.GetTime()
        if now - stop_watch_5 > 5 then
            stop_watch_5 = now
            local x,z = data_pos.x, data_pos.z
            local flag
            for id, data in pairs(map_data)do
                if type(data) == "table" then
                    local dx, dz = tonumber(data.x), tonumber(data.z)
                    if dx and dz and data.c == iscave and GetDist(x,z,dx,dz)<range then
                        if not data.l then
                            map_data[id] = nil
                            flag = true
                        elseif data.m then
                            local ent = e_util:FindEnt({x = dx, z = dz}, data.p, 1, {"huxi"}, {})
                            if not ent and data.p then
                                local tex =  data.p..".tex"
                                local h_data = d_util:GetIconData()
                                for _, line in pairs(h_data)do
                                    if line.i == tex then return end
                                end
                                local p = GLOBAL.SpawnPrefab(data.p)
                                if p then
                                    p.Transform:SetPosition(dx, 0, dz)
                                end
                            end
                        end
                    end
                end
            end
            if flag then
                local ents = GLOBAL.TheSim:FindEntities(x, 0, z, range, nil, {'FX','DECOR','INLIMBO','NOCLICK', 'player', 'NOBLOCK'})
                for _,ent in pairs(ents)do
                    local prefab = ent.prefab
                    if table.contains(prefabs, prefab)then
                        local dx,dz = getPos(ent)
                        if dx and dz and not GetLeader(ent) then
                            table.insert(map_data, {
                                c = iscave,
                                x = dx,
                                z = dz,
                                p = prefab
                            })
                        end
                    end
                end
            end
        end
    end)
end)
-- 加载更多图标以及中键隐藏
local MoreIcons = require "widgets/automapicons"
AddClassPostConstruct("screens/mapscreen", function(self)
    local _OnMouseButton = self.OnMouseButton
    function self.OnMouseButton(self, button, down, ...)
        if button == GLOBAL.MOUSEBUTTON_MIDDLE and down then
            local mapbutton = t_util:GetChild(t_util:GetChild(t_util:GetChild(self, "br_root"), "br_scale_root"), "Map Controls")
            if mapbutton and mapbutton.focus and self.moremapicons then
                self.moremapicons:SwitchHide()
            end
        end
        return _OnMouseButton(self, button, down, ...)
    end
    if self.moremapicons then
        self.moremapicons:Kill()
    end
    self.moremapicons = self:AddChild(MoreIcons(self, iscave))
end)
-- 适配鹰眼模式
AddClassPostConstruct("screens/playerhud", function(self)
    if self.moremapicons then
        self.moremapicons:Kill()
    end
    self.moremapicons = self:AddChild(MoreIcons(self))
end)

-- 面板功能
DEAR_BTNS:AddDearBtn(GLOBAL.GetInventoryItemAtlas("greenmooneye.tex"), "greenmooneye.tex", "地图图标", "更多图标设置，仅对已存在的图标显示", true, function()
    GLOBAL.TheFrontEnd:PushScreen(require("screens/moremapicons")())
end)
-----------------------------------------核心原理-----------------------------------------------

